﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace StudyDemo.Attributes
{
    public class CustomeAttribute
    {
        public static string GetTableName<T>(T mode)
            where T : class
        {
            Type type = typeof(T);
            if (type.IsDefined(typeof(TableAttribute), true))  //判断T是否有TableAttribute
            {
                //返回TableAttribute的Name属性值
                var attribute = type.GetCustomAttributes(typeof(TableAttribute), true);

                return ((TableAttribute)attribute[0]).TableName; ;
            }
            else
            {
                //返回类名
                return type.Name;
            }
        }

        public static bool Validate<T>(T mode)
        {
            //获取T的所有属性和特性
            PropertyInfo[] properties = typeof(T).GetProperties();

            foreach (var property in properties)
            {
                //判断属性是否有RequiredAttribute特性
                if (property.IsDefined(typeof(CommonValidateAttribute), true))
                {
                    var attributes = property.GetCustomAttributes(typeof(CommonValidateAttribute), true);
                    foreach (var item in attributes)
                    {
                        var attribute = item as CommonValidateAttribute;
                        if (!attribute.IsValidate(property.GetValue(mode)))
                        {
                            return false;
                        }
                    }
                }
            }

            return true;
        }
    }
}
